<template>
  <u-popup
    v-model="comShow"
    mode="bottom"
    width="750"
    height="800"
    :closeable="true"
    :mask-close-able="false"
    border-radius="15"
    @close="onClose"
  >
    <view class="popup-box">
      <slot></slot>
      <view v-if="!freePay">
        <p>请选择支付方式</p>
        <!-- #ifdef MP-WEIXIN -->
        <view @click="payMethod = 'wx_lite'" class="pay-method">
          <view class="pay-method-left">
            <image src="/static/wxzf.png" mode="aspectFill"></image>
            <text style="margin-left: 15rpx; font-size: 32rpx">微信支付</text>
          </view>
          <u-icon
            v-if="payMethod == 'wx_lite'"
            class="pay-method-right"
            name="/static/selected.png"
            size="36"
          ></u-icon>
          <u-icon v-else class="pay-method-right" name="/static/unselect.png" size="36"></u-icon>
        </view>
        <!-- #endif -->
        <!-- <view @click="payMethod = 'alipay_app'" class="pay-method">
          <view class="pay-method-left">
            <image src="/static/alipay.png" mode="aspectFill"></image>
            <text style="margin-left: 15rpx; font-size: 32rpx">支付宝支付</text>
          </view>
          <u-icon
            v-if="payMethod == 'alipay_app'"
            class="pay-method-right"
            name="/static/selected.png"
            size="40"
          ></u-icon>
          <u-icon v-else class="pay-method-right" name="/static/unselect.png" size="36"></u-icon>
        </view>
        <view @click="payMethod = 'union_pay'" class="pay-method">
          <view class="pay-method-left">
            <image src="/static/yhk.png" mode="aspectFill"></image>
            <text style="margin-left: 15rpx; font-size: 32rpx">银联支付</text>
          </view>
          <u-icon
            v-if="payMethod == 'union_pay'"
            class="pay-method-right"
            name="/static/selected.png"
            size="40"
          ></u-icon>
          <u-icon v-else class="pay-method-right" name="/static/unselect.png" size="36"></u-icon>
        </view> -->
        <view @click="payMethod = 'wallet'" class="pay-method">
          <view class="pay-method-left">
            <image src="/static/yezf.png" mode="aspectFill"></image>
            <text style="margin-left: 15rpx; font-size: 32rpx">钱包支付</text>
            <text v-if="userInfo" style="color: darkgray; font-size: 30rpx"
              >(余额{{ (balance * 0.01).toFixed(2) }}元)
            </text>
            <text v-else style="color: darkgray; font-size: 30rpx">(需要登录)</text>
          </view>
          <u-icon
            v-if="payMethod == 'wallet'"
            class="pay-method-right"
            name="/static/selected.png"
            size="36"
          ></u-icon>
          <u-icon v-else class="pay-method-right" name="/static/unselect.png" size="36"></u-icon>
        </view>
        <!-- #ifdef H5 -->
        <view @click="payMethod = 'mock'" class="pay-method">
          <view class="pay-method-left">
            <image src="/static/mock.png" mode="aspectFill"></image>
            <text style="margin-left: 15rpx; font-size: 32rpx">模拟支付</text>
          </view>
          <u-icon
            v-if="payMethod == 'mock'"
            class="pay-method-right"
            name="/static/selected.png"
            size="36"
          ></u-icon>
          <u-icon v-else class="pay-method-right" name="/static/unselect.png" size="36"></u-icon>
        </view>
        <!-- #endif -->
        <view class="fixed-wapper">
          <view class="submit-btn" @click="confirmPay"> 立即付款</view>
        </view>
      </view>
      <view v-else>
        <view @click="payMethod = 'free'" class="pay-method">
          <view class="pay-method-left">
            <image src="/static/free.png" mode="aspectFill"></image>
            <text style="margin-left: 15rpx; font-size: 32rpx">免费支付</text>
          </view>
          <u-icon class="pay-method-right" name="/static/selected.png" size="36"></u-icon>
        </view>
        <view class="fixed-wapper">
          <view class="submit-btn" @click="confirmPay"> 立即付款</view>
        </view>
      </view>
    </view>
  </u-popup>
</template>

<script>
export default {
  name: 'PayPopup',
  data() {
    return {
      payMethod: null,
      dataShow: false,
      payOrderId: '',
      openid: '',
      freePay: false,
      returnPage: null,
      reqSuccess: false,
      userInfo: null,
      balance: 0,
      disable: false
    }
  },
  computed: {
    comShow: {
      get() {
        return this.dataShow
      },
      set(val) {
        this.dataShow = val
      }
    }
  },
  methods: {
    /**
     *  打开支付弹窗
     *
     * @param tradeNo 交易单号
     * @param openid 微信用户的 openid
     * @param freePay 是否免支付
     * @param returnPage 返回页面
     */
    open(tradeNo, openid = '', freePay = false, returnPage = null) {
      this.dataShow = true
      this.payOrderId = tradeNo
      this.openid = openid
      this.freePay = freePay
      this.returnPage = returnPage
      this.userInfo = uni.getStorageSync('userInfo')
      this.getBalance()
    },
    getBalance() {
      this.$u.get('/app-api/pay/wallet/get').then((res) => {
        if (res.code === 0) {
          this.balance = res.data.balance
        }
      })
    },
    confirmPay() {
      // this.$u.get("/app-api/pay/channel/get-enable-code-list").then(res => {
      // 	console.log(res.data)
      // })
      if (!this.payMethod || !this.payMethod.length) {
        this.$u.toast('请选择支付方式')
        return
      }
      if (this.payMethod === 'wallet' || this.payMethod === 'mock' || this.payMethod === 'free') {
        this.doPay('')
        return
      }
      if (this.payMethod !== 'wx_lite' && this.payMethod !== 'mallbook_wx_lite') {
        this.$u.toast('不支持的支付渠道：' + this.payMethod)
        return
      }
      if (!this.openid) {
        this.openid = uni.getStorageSync('wx_openid')
      }
      if (!this.openid) {
        this.openid = this.userInfo?.wxOpenId
      }
      if (this.openid) {
        this.doPay('')
        return
      }
      // 使用微信静默授权换取未登录情况下发起支付所需的 openid
      uni.login({
        provider: 'weixin',
        success: (res) => {
          console.debug('weixin login: ' + JSON.stringify(res))
          this.doPay(res.code)
        },
        fail: (err) => {
          console.log('微信支付授权失败', err)
          this.$u.toast('微信支付授权失败')
        }
      })
    },
    doPay(authCode) {
      if (this.payMethod === 'wallet' && !this.userInfo) {
        this.$u.toast('登录后才能使用钱包支付')
        return
      }
      if (this.disable) {
        this.$u.toast('支付请求中，请稍候')
        return
      }
      this.disable = true
      this.$u
        .post('/app-api/pay/order/submit', {
          tradeNo: this.payOrderId,
          channelCode: this.payMethod,
          channelExtras: {
            auth_code: authCode || '',
            openid: this.openid || ''
          }
        })
        .then((res) => {
          this.disable = false
          if (res.code !== 0) {
            this.$u.toast(res.msg || '支付请求失败，请重新支付')
            return
          }
          if (
            this.payMethod === 'wallet' ||
            this.payMethod === 'mock' ||
            this.payMethod === 'free'
          ) {
            this.payCallbcak(res)
            return
          }
          const displayContent = res.data.displayContent || res.data.data.displayContent
          console.debug('wxpay displayContent=' + displayContent)
          this.requestWxPay(JSON.parse(displayContent))
        })
        .catch((err) => {
          this.disable = false
          console.warn('支付请求出错：', err)
          this.$u.toast('支付请求出错，请重新支付')
        })
    },
    requestWxPay(payParams) {
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: payParams.timeStamp,
        nonceStr: payParams.nonceStr,
        package: payParams.package,
        signType: payParams.signType,
        paySign: payParams.paySign,
        success: (res) => {
          console.log('发起支付成功', res)
          this.payCallbcak({
            code: 0,
            msg: '发起支付成功',
            data: res
          })
        },
        fail: (err) => {
          console.log('发起支付出错', err)
          this.$u.toast('发起支付失败，请重新支付')
        }
      })
    },
    payCallbcak(res) {
      if (res.code !== 0) {
        this.$u.toast(res.msg)
        this.reqSuccess = false
        return
      }
      this.reqSuccess = true
      this.onPayResult()
    },
    onClose() {
      this.dataShow = false
      if (this.freePay) {
        this.payMethod = 'free'
        this.doPay('')
        this.$emit('close')
        return
      }
      this.$emit('close')
    },
    onPayResult() {
      let url = '/universal/pay-result/pay-result?tradeNo=' + this.payOrderId
      if (this.returnPage) {
        url += '&returnPage=' + encodeURIComponent(this.returnPage)
      }
      uni.redirectTo({
        url: url
      })
    }
  }
}
</script>

<style>
@import url('@/style/btn.css');

.popup-box {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
}

.pay-method {
  overflow: auto;
  padding: 25rpx 20rpx;
}

.pay-method-left {
  float: left;
  display: flex;
  align-items: center;
}

.pay-method-left image {
  width: 80rpx;
  height: 80rpx;
}

.pay-method-right {
  float: right;
}

.submit-btn {
  margin-bottom: 20rpx;
}
</style>
